from autoui.core.doweb import DoWeb,socket_port,redirect
from selenium import webdriver
from autoui.config.seleniumf import driver_path
import time
import subprocess
import os


class control:
    def __init__(self):
        self.driver = None
        self.web=DoWeb()
        self.proxy=None
        self.proxy_port=18855

    def start_chrome(self):
        try:
            self.driver.maximize_window()
        except :
            self.close_chrome()
            # self.driver=None
        
        if self.driver is None:
            chrome_options = webdriver.ChromeOptions()
            chrome_options.add_argument(
                '--start-maximized')  # 最大化运行（全屏窗口）,不设置，取元素会报错
            chrome_options.add_argument('--incognito')  # 隐身模式（无痕模式）
            chrome_options.add_argument(
                '--proxy-server={host}:{port}'.format(host="localhost", port=self.proxy_port))
            chrome_options.add_experimental_option(
                'excludeSwitches', ['enable-logging'])  # 去除控制台报错
            try:
                print()
                self.driver = webdriver.Chrome(
                    executable_path=driver_path, options=chrome_options)
                return 'ok'
            except Exception as e:
                print(e)
                # print('driver start failed')
                return 'driver start failed'
        else:
            print('driver is running')
            return 'driver is running'

    def close_chrome(self):
        if self.driver is not None:
            self.driver.quit()
            self.driver=None
            return 'ok'
        else:
            return 'no stop'

    def add_web_script(self):
        js2='''
        var ele = '';
        function over(x) {
            x.style.backgroundColor = 'RGB(240,255,240,0.5)';
        };
        function postsele (data) {
      　　　　url = '/myseleniumelement';
      　　　　xhr = new XMLHttpRequest();

      　　xhr.open('post', url,true);
      　　xhr.setRequestHeader('Content-type', 'application/json');
      　　xhr.send(data);
      };

        function leave(x) {
            x.style.backgroundColor = '';
        };
        function getlocal() {
            re=[];
            
            var id = ele.id;
            if (id != '') {
                var res = {};
                res['type'] = 'id';
                res['num'] = 1;
                res['val'] = id;
                res['index'] = 0;

                console.log(res);
                re.push(res);
            

            }
            var name = ele.name;
            if (name!=null &&name != '') {
                l = document.getElementsByName(name);
                if (l.length == 1) {
                    var res = {};
                    res['type'] = 'name';
                    res['num'] = 1;
                    res['val'] = name;
                    res['index'] = 0;
                    console.log(res);
                    re.push(res);


                } else {
                    if (l.length != 0) {
                        for (var i = 0; i < l.length; i++) {
                            if (l[i] == ele) {
                                var res = {};
                                res['type'] = 'name';
                                res['num'] = l.length;
                                res['val'] = name;
                                res['index'] = i;
                                console.log(res);
                                re.push(res);
                            }

                        }
                    }
                }

            }

            var name = ele.className;

            if (name!=null &&name != '' && typeof(name)=='string') {
                n=name.split(' ');
                l =9999;
                cn='';
                for(var i=0;i<n.length;i++){
                    l2 = document.getElementsByClassName(n[i]);
                    if(l2.length<l){
                        l=l2.length;
                        cn=n[i];
                    }
                }
                l = document.getElementsByClassName(cn);
                if (l.length == 1) {
                    var res = {};
                    res['type'] = 'class';
                    res['num'] = 1;
                    res['val'] = cn;
                    res['index'] = 0;
                    console.log(res);
                    re.push(res);

                } else {
                    if (l.length != 0) {
                        for (var i = 0; i < l.length; i++) {
                            if (l[i] == ele) {
                                var res = {};
                                res['type'] = 'class';
                                res['num'] = l.length;
                                res['val'] = cn;
                                res['index'] = i;
                                console.log(res);
                                re.push(res);
                            }

                        }
                    }
                }

            }
            var name = ele.tagName;
            if (name!=null &&name != '') {
                l = document.getElementsByTagName(name);
                if (l.length == 1) {
                    var res = {};
                    res['type'] = 'tag';
                    res['num'] = 1;
                    res['val'] = name;
                    res['index'] = 0;
                    console.log(res);
                    re.push(res);

                } else {
                    if (l.length != 0) {
                        for (var i = 0; i < l.length; i++) {
                            if (l[i] == ele) {
                                var res = {};
                                res['type'] = 'tag';
                                res['num'] = l.length;
                                res['val'] = name;
                                res['index'] = i;
                                console.log(res);
                                re.push(res);
                            }

                        }
                    }
                }

            }
            if(re.length==0) {
                alert('无法识别');
                return [];
            }else{
                return re;
            }
            



        };
        function highlight() {
            ele.classList.add('highsele');
        };
        function nohighlight() {
            ele.classList.remove('highsele');
        };
        function gettext() {
            t = ele.tagName;

            if (t == 'INPUT') {
                var ee2 = ele;

                while (true) {
                    if (ee2.tagName == 'BODY' || ee2.tagName == 'HTML') {
                        console.log('定位失败');
                        return '定位失败';
                    }
                    var ee3 = ee2.parentElement;

                    if (ee3.innerText != '') {
                        var ee4 = ee2.previousElementSibling;

                        if (ee4 != null && ee4.innerText != '') {
                            console.log(ee4.innerText);
                            return ee4.innerText;
                        } else {
                            ee4 = ee2.nextElementSibling;
                            if (ee4 != null && ee4.innerText != '') {
                                console.log(ee4.innerText);
                                return ee4.innerText;
                            } else {

                                console.log(ee3.innerText);
                                return ee3.innerText;
                            }

                        }
                    } else {
                        ee2 = ee3;
                    }
                }



            } else {
                var t=ele.innerText;
                if (typeof(ele) == 'undefined'){
                console.log('无法获取名称');
                return '无法获取名称';
                }
                console.log(t);
                return t;
                
            }
        };
        function getinfo(){
            var info ={name:gettext(),local:getlocal()};
            console.log(info);
        };
        function postinfo(){
            var info ={name:gettext(),local:getlocal()};
            postsele(JSON.stringify(info));
        };
        '''
        js = '''
        s = document.createElement('script');
        s.textContent = "function addNewStyle(newStyle){var styleElement = document.getElementById('styles_js');            if (!styleElement) {                styleElement = document.createElement('style');                styleElement.type = 'text/css';                styleElement.id = 'styles_js';                document.getElementsByTagName('head')[0].appendChild(styleElement);            }          styleElement.appendChild(document.createTextNode(newStyle));};     function over(x) { x.style.backgroundColor = 'RGB(240,255,240,0.5)' };    function leave(x) { x.style.backgroundColor = ''; }; %s ";
        document.body.appendChild(s);
        ''' % self.getString(js2)
        self.driver.execute_script(js)
        # print('js1')
        # driver.execute_script(
        #     "function addNewStyle(newStyle) {             var styleElement = document.getElementById('styles_js');            if (!styleElement) {                styleElement = document.createElement('style');                styleElement.type = 'text/css';                styleElement.id = 'styles_js';                document.getElementsByTagName('head')[0].appendChild(styleElement);            }          styleElement.appendChild(document.createTextNode(newStyle));}")
        time.sleep(1)
        css='''
        .seleul {
                display: none;
                box-shadow: 0px 0px 5px #f4979a;
                text-align: center;
                width: 160px;
                height: 205px;
                position: absolute;
                margin: 0;
                padding: 0;
            }

            .seleli {
                height: 50px;
                line-height: 50px;
                font-size: 16px;
                list-style: none;
                border: 1px solid #eee;
            }
            .highsele{
                background-color: #f4979a;
            }
        '''
        html='''
        <ul id='selelist' class='seleul' unselectable='on' onselectstart='return false;' style='-moz-user-select:none;z-index: 9999;'>
            <li class='seleli' onmouseover='over(this)' onmouseleave='leave(this)' onclick='getinfo()'>获取信息</li>
            <li class='seleli' onmouseover='over(this)' onmouseleave='leave(this)' onclick='postinfo()'>发送信息</li>
            <li class='seleli' onmouseover='over(this)' onmouseleave='leave(this)' onclick='highlight()'>设置高亮</li>
            <li class='seleli' onmouseover='over(this)' onmouseleave='leave(this)'  onclick='nohighlight()'>取消高亮</li>
        </ul>
        '''
        # driver.execute_script(
        #     "addNewStyle('.seleul{ display: none; box-shadow: 0px 0px 5px #f4979a; text-align: center; width: 160px; height: 205px; position: absolute; margin: 0; padding: 0;}')")
        self.driver.execute_script("addNewStyle('"+self.getString(css)+"')")
        print('css')
        time.sleep(1)
        self.driver.execute_script("var aa=document.createElement('div');"+'aa.innerHTML="'+self.getString(html)+'";document.body.insertBefore(aa,document.body.firstChild)')
        # time.sleep(1)
        # driver.execute_script()
        print('html')

        # driver.execute_script(
        #     "addNewStyle('.seleli{ height: 50px; line-height: 50px; font-size: 16px; list-style: none; border: 1px solid #eee;}')")
        # time.sleep(1)
        # driver.execute_script("aa=document.createElement('div')")
        # time.sleep(1)
        # driver.execute_script('aa.innerHTML=\'<ul id="listsele" class="seleul" unselectable="on" onselectstart="return false;" style="-moz-user-select:none;z-index: 9999;"><li class="seleli" onmouseover="over(this)" onmouseleave="leave(this)">选项一</li><li class="seleli" onmouseover="over(this)" onmouseleave="leave(this)">选项二</li><li class="seleli" onmouseover="over(this)" onmouseleave="leave(this)">选项三</li><li class="seleli" onmouseover="over(this)" onmouseleave="leave(this)">选项四</li></ul>\'')
        # time.sleep(1)
        # driver.execute_script(
        #     "document.body.insertBefore(aa,document.body.firstChild)")
        # time.sleep(1)
        # driver.execute_script(
        #     "var el=document.getElementById('listsele');document.oncontextmenu=function(ev){ var ev=ev||event;  console.log(ev);   ev.preventDefault();var x=ev.pageX; var y=ev.pageY; el.style.display='block'; el.style.left=x+'px'; el.style.top=y+'px'; document.onclick=function(){   el.style.display='none'; }}")
        
        js='''
        
    
        
        document.oncontextmenu = function (ev) {
            var el = document.getElementById('selelist'); 
            var ev = ev || event; 
            ev.preventDefault();
            ele = ev.toElement;
            var x = ev.pageX;
            var y = ev.pageY;
            el.style.display = 'block';
            el.style.left = x + 'px';
            el.style.top = y + 'px';
            document.onclick = function () {  
                el.style.display = 'none';
            }
        }
        '''
        # print(getString(js))
        self.driver.execute_script(self.getString(js))
        print('js2')

        self.driver.execute_script('console.log("ok")')
        return 'ok'

    def start_proxy(self):
        if self.proxy is None:
            aa=[]
            # r'"C:\Users\lixuecheng\Envs\testautoui\autoui\static\mitmdump.exe" -q -s "C:\Users\lixuecheng\Envs\testautoui\autoui\static\mitmtest.py" -p '+
            aa.append(r'C:\Users\lixuecheng\Envs\testautoui\autoui\static\mitmdump.exe')
            aa.append('-q')
            aa.append('-s')
            aa.append(r'C:\Users\lixuecheng\Envs\testautoui\autoui\static\mitmtest.py')
            aa.append('-p')
            aa.append(str(self.proxy_port))
            self.proxy=subprocess.Popen(aa, close_fds=True)
            return 'ok'
        else:
            return 'no'

    def close_proxy(self):
        if self.proxy is not None:
            self.proxy.terminate()
            # a=os.popen('taskkill /pid {} /f'.format(str(self.proxy.pid)))
            # b=a.read()
            self.proxy=None
            # print(b)
            return  'ok'
        else:
            return 'no'
        # print(self.proxy)
        # self.proxy.terminate()
        # self.proxy=None

    @staticmethod
    def getString(s):
        return s.replace('\r', '').replace('\n', ' ')
    @staticmethod
    def get_port(p):
        return socket_port('localhost',int(p))

    def index_html(self):
        return redirect('/index.html')


    def web_start(self):
        # self.driver=driver

        
        print(self.proxy_port)
        self.web.add_route('/',self.index_html)
        self.web.add_route('/chrome/start',self.start_chrome)
        self.web.add_route('/chrome/stop',self.close_chrome)
        self.web.add_route('/proxy/start',self.start_proxy)
        self.web.add_route('/proxy/stop',self.close_proxy)
        self.web.add_route('/script/start',self.add_web_script)


        self.web.add_static_file('/index.html')
        
        
        self.web.add_close_func(self.close_chrome,self.close_proxy)
        self.web.start()


control().web_start()



